package com.example.sud_game_plus

import android.util.Log
import android.widget.FrameLayout
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import tech.sud.mgp.core.ISudFSMMG
import tech.sud.mgp.core.ISudFSMStateHandle
import tech.sud.mgp.core.ISudFSTAPP
import tech.sud.mgp.core.ISudListenerNotifyStateChange
import tech.sud.mgp.core.SudLoadMGParamModel
import tech.sud.mgp.core.SudMGP

class GameManager {

    var isLifecycleRegistered: Boolean = false
    var gameContainer: FrameLayout? = null
    private var _gameApp: ISudFSTAPP? = null // game interface


    companion object{
//        private var instance:GameManager?=null
//        @Synchronized
//        fun get():GameManager{
//            if(null==instance) instance=GameManager()
//            return instance as GameManager
//        }

        @Volatile
        private var instance: GameManager? = null

        fun get(): GameManager {
            return instance ?: synchronized(this) {
                instance ?: GameManager().also { instance = it }
            }
        }
    }

    fun playMG(){
        if (_gameApp != null) {
            _gameApp?.playMG()
        }
    }
    fun pauseMG(){
        if (_gameApp != null) {
            _gameApp?.pauseMG()
        }
    }
    fun  destroyMG(){
        if (_gameApp != null) {
            _gameApp?.destroyMG()
            _gameApp = null

            // 清理全局容器内视图，避免内存泄漏
            gameContainer?.removeAllViews()
            Log.d("GameManager", "Game destroyed and container cleared")
        }
    }

    fun updateCode( code:String?,var2: ISudListenerNotifyStateChange?) {
        if (_gameApp != null) {
            _gameApp?.updateCode(code ?: "", var2)
        }
    }

    fun notifyStateChange( state:String,dataJson:String,var3:ISudListenerNotifyStateChange?) {
        if (_gameApp != null) {
            _gameApp?.notifyStateChange(state, dataJson, var3)
        }
    }

    /**
     * 加载游戏，如果已经加载则复用
     */
    @Synchronized
    fun loadGame(model: SudLoadMGParamModel, fsmMG: ISudFSMMG): ISudFSTAPP {
//        _gameApp = SudMGP.loadMG(model,fsmMG)
//        return  _gameApp!!
        if (_gameApp != null) {
            Log.w("GameManager", "Game already loaded, reuse existing instance")
            return _gameApp!!
        }
        _gameApp = SudMGP.loadMG(model, fsmMG)
        Log.d("GameManager", "Game loaded successfully")
        return _gameApp!!
    }

}


